package com.zhang.third.day04;

import com.zhang.third.utils.ClickEventSource;
import com.zhang.third.utils.Event;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 统计每个用户访问url信息 限流输出
 * @author: zhang
 * @date: 2022/4/7 09:43
 */
public class Example1_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickEventSource())
                .keyBy(r -> r.key)
                .process(new KeyedProcessFunction<String, Event, String>() {
                    // 声明MapState
                    private MapState<String, Long> mapState;
                    // 声明ValueState c存储定时器时间戳
                    private ValueState<Long> timerState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().getMapState(
                                new MapStateDescriptor<String, Long>(
                                        "url-count",
                                        Types.STRING,
                                        Types.LONG
                                )
                        );
                        timerState = getRuntimeContext().getState(
                                new ValueStateDescriptor<Long>(
                                        "time-state",
                                        Types.LONG
                                )
                        );
                    }

                    @Override
                    public void processElement(Event value, KeyedProcessFunction<String, Event, String>.Context ctx, Collector<String> out) throws Exception {
                        String key = value.value; // url
                        if (!mapState.contains(key)) {
                            mapState.put(key, 1L);
                        } else {
                            mapState.put(key, mapState.get(key) + 1L);
                        }
                        if (timerState.value() == null) {
                            long currTs = ctx.timerService().currentProcessingTime();
                            long tenSecLater = currTs + 10 * 1000L;
                            ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                            timerState.update(tenSecLater);
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<String, Event, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                        StringBuilder result = new StringBuilder();
                        result.append(ctx.getCurrentKey() + " {\n");
                        for (String url : mapState.keys()) {
                            result.append("  " + url + "=>" + mapState.get(url) + ",\n");
                        }
                        result.append("}\n");
                        out.collect(result.toString());
                        timerState.clear();
                        mapState.remove(ctx.getCurrentKey());
                    }
                })
                .print();

        env.execute();
    }
}
